// pages/bluetooth/bluetooth.js
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i
    }
  }
  return -1
}

const Util = require('../../utils/util');
var isHidePage = false;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    stopText: '停止搜索',
    devices: [],
    statusImg: '../../images/ic_empty.png',
    statusText: '暂无发现附近有蓝牙设备',
    key: '',
    index:0,
    filterDeviceName:'SHMX-SET9'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let index = options.index;
    wx.setNavigationBarTitle({
      title: '选择' + (index == 0 ? '方向盘' : '座椅') + '对应的蓝牙设备',
    })
    this.setData({
      index:index,
      filterDeviceName:index == 0 ? 'SHMX-SET' : 'HC-08'
    })
    //获取当前位置信息，因为有些手机不开启定位权限的话会造成定位不准确从而不能精准搜索到附近的蓝牙设备
    this.checkLocation();
    this.onCheckBluetoothStatusChange(); //监听手机蓝牙状态变化,需要打开蓝牙成功后才能监听
  },

  checkLocation: function () {
    let _this = this;
    _this._discoveryStarted = false;
    Util.showLoading('正在初始化...');
    _this.setData({
      statusText: '正在初始化位置服务...',
      devices: []
    });
    wx.getSetting({
      success(res) {
        Util.hideLoading();
        if (res.authSetting['scope.userLocation']) {
          _this.checkBluetooth();
        } else {
          _this.authorizeLocation();
        }
      }
    });
  },

  authorizeLocation() {
    let _this = this;
    wx.authorize({
      scope: 'scope.userLocation',
      success() {
        _this.checkBluetooth();
      },
      fail(errMsg) {
        _this.authorizeLocationFail();
      }
    })
  },

  authorizeLocationFail() {
    let _this = this;
    _this.setData({
      statusText: '位置授权失败!'
    });
    // Util.showCommonModal('位置授权失败', '您已拒绝了本次小程序使用的位置授权，本小程序需要使用位置功能，请在设置中开启位置权限,马上设置?', res => {
    //   if (res.confirm) {
    //     _this.openSetting('location');
    //   }
    // });
  },

  openSetting(index) {
    let _this = this;
    wx.openSetting({
      success: res => {
        if (index == 'location') {
          if (res.authSetting['scope.userLocation'] || res.authSetting['scope.userLocationBackground']) {
            _this.checkBluetooth();
          } else {
            _this.authorizeLocationFail();
          }
        } else if (index == 'bluetooth') {
          if (res.authSetting['scope.bluetooth']) {
            _this.checkBluetooth();
          } else {
            _this.authorizeBluetoothAdapter('蓝牙权限未授权');
          }
        }
      },
      fail: err => {
        if (index == 'location') {
          _this.authorizeLocationFail();
        } else if (index == 'bluetooth') {
          _this.authorizeBluetoothAdapter('蓝牙权限未授权');
        }
      }
    });
  },

  authorizeBluetoothAdapter(errMsg) {
    let _this = this;
    _this.setData({
      statusText: errMsg
    });
    if (!errMsg.includes('目前蓝牙调试功能暂不支持 Mac 以外的平台')) {
      // Util.showCommonModal('蓝牙授权失败', '您没有授权蓝牙权限，本小程序需要使用蓝牙功能，请在设置中开启蓝牙权限,马上设置?', res => {
      //   if (res.confirm) {
      //     _this.openSetting('bluetooth');
      //   }
      // });
    }
  },

  checkBluetooth: function () {
    let _this = this;
    let statusMeg = '正在检查手机蓝牙...';
    Util.showLoading(statusMeg);
    _this.setData({
      devices: [],
      statusText: statusMeg
    });
    wx.openBluetoothAdapter({
      success: function (res) {
        Util.hideLoading();
        _this.startBluetoothDevicesDiscovery();
      },
      fail: function (res) {
        console.log(res)
        let errMsg = res.errMsg;
        Util.hideLoading();
        if (res.errCode === 10001) {
          _this.showBluetoothClose();
        } else {
          _this.authorizeBluetoothAdapter(errMsg);
        }
      }
    });
  },

  onCheckBluetoothStatusChange() {
    let _this = this;
    wx.onBluetoothAdapterStateChange(function (res) {
      console.log(res);
      console.log('_this.isHidePage='+_this.isHidePage);
      if (!_this.isHidePage) {
        if (res && res.available) {
          _this.setData({
            available: res.available
          });
          if (!res.discovering && !_this._discoveryStarted) {
            _this.checkBluetooth();
          }
        } else {
          _this.showBluetoothClose();
        }
      }
    });
  },

  onHide() {
    this.isHidePage = true;
  },

  onShow() {
    this.isHidePage = false;
  },

  showBluetoothClose() {
    let _this = this;
    _this._discoveryStarted = false;
    let msg = '检测到您的手机蓝牙功能未开启，请打开手机蓝牙后再试，谢谢!';
    _this.setData({
      devices: [],
      statusText: msg
    });
    //Util.showCommonModal('温馨提示', msg, res => {});
  },

  startBluetoothDevicesDiscovery() {
    let _this = this;
    let statusMeg = '正在搜索目标设备...';
    _this._discoveryStarted = false;
    Util.showLoading(statusMeg);
    _this.setData({
      statusText: statusMeg,
      devices: []
    });
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        Util.hideLoading();
        _this.onBluetoothDeviceFound();
      },
    })
  },

  onBluetoothDeviceFound() {
    let _this = this;
    _this._discoveryStarted = true;
    _this.setData({
      stopText: '停止搜索',
      statusText: '暂无数据',
    });
    let filterDeviceName = _this.data;
    let key = _this.data.filterDeviceName;
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        let foundDevices = _this.data.devices;
        if (device.name.indexOf(key) >= 0) {
          const idx = inArray(foundDevices, 'deviceId', device.deviceId);
          if (idx === -1) {
            foundDevices[foundDevices.length] = device;
          } else {
            foundDevices[idx] = device;
            _this.onFindDevice(device);
          }
          _this.setData({
            devices: foundDevices
          });
        }
      })
    })
  },

  onFindDevice(device){
    this.onStopBluetoothDevicesDiscovery();
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    prevPage.onSelectBluetoothDevice(device.name, device.deviceId);
    Util.goBack();
  },

  stopBluetoothDevicesDiscovery() {
    let _this = this;
    if (_this.data.stopText == '停止搜索') {
      _this._discoveryStarted = true;
      _this.setData({
        stopText: '重新搜索'
      });
      _this.onStopBluetoothDevicesDiscovery();
    } else {
      _this.startBluetoothDevicesDiscovery();
    }
  },

  onReLoad: function () {
    this.checkLocation();
  },

  onStopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery({
      complete: () => {

      }
    });
   // wx.offBluetoothAdapterStateChange();
  },

  getItem: function (e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;
    let item = _this.data.devices[index];
    let name = item.name;
    _this.onStopBluetoothDevicesDiscovery();
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    prevPage.onSelectBluetoothDevice(name, item.deviceId);
    Util.goBack();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.onStopBluetoothDevicesDiscovery();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.checkLocation();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})